package leetcode;

public class Lc162 {

    public int findPeakElement(int[] nums) {

        int l = 0, r = nums.length - 1;
        if (r == 0) return 0;

        int index = binarySearch(nums, 0, r);

        return index;
    }
    public int binarySearch(int[] nums, int l, int r) {
        if (l > r)
            return -1;
        int mid = (l + r) / 2;
        if (mid == 0) {
            if (nums[0] > nums[1])
                return 0;
            return binarySearch(nums, mid + 1, r);
        } else if (mid == nums.length - 1) {
            if (nums[mid] > nums[mid - 1]) {
                return mid;
            }
            return binarySearch(nums, l, mid - 1);
        } else {
            if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
                return mid;
            }
            int index = binarySearch(nums, l, mid - 1);
            if (index != -1)
                return index;
            return binarySearch(nums, mid + 1, r);
        }
    }
}
